package com.heima.wemedia.config;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


/**
 * 自定义拦截器
 * 用于存储用户登陆信息
 *
 * @author zhouao
 * @date 2022/06/14
 */
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取token
        String token = request.getHeader("token");
        //如果元素不为空则将数据添加进去
        Optional<String> parm = Optional.ofNullable(token);
        //如果有元素则添加到全局线程常量中
        if (parm.isPresent()) {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //解析token
            Integer userId = (Integer) claimsBody.get("id");
            WmUser wmUser = new WmUser();
            wmUser.setId(userId);
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        WmThreadLocalUtil.clear();
    }

}
